﻿using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace RSSR
{
    public partial class DetailsPage : PhoneApplicationPage
    {
        RSSFeed CurrentFeed;
        WebClient aWebClient = new WebClient();
        public DetailsPage()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            progressBar1.Value += 10;
            aWebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(aWebClient_DownloadProgressChanged);
            aWebClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(aWebClient_DownloadStringCompleted);
            
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            CurrentFeed = (RSSFeed)root.DataContext;
            ListName.Text = CurrentFeed.FeedTitle;
            aWebClient.DownloadStringAsync(new Uri( CurrentFeed.FeedURL));
        }

        void aWebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            progressBar1.Value = 0;
            
            if (e.Error != null)
                return;

            System.Xml.Linq.XElement MyXElement = System.Xml.Linq.XElement.Parse(e.Result);

            listBox1.ItemsSource = from RSSElement in MyXElement.Descendants("item")
                                   select new RSSItem
                                   {
                                       Title = RSSElement.Element("title").Value,
                                       Description= RSSElement.Element("description").Value.Substring(0,200),
                                       URL = RSSElement.Element("link").Value
                                   };
        }

        void aWebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            if (progressBar1.Value == 100) progressBar1.Value = 0; else progressBar1.Value += 10;

        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Todo : start the browser.
        }
    }
}